const pool = require('../config/db');
const archiver = require('archiver');
const fs = require('fs');
const path = require('path');

// 递归获取文件夹内所有内容
const getFolderContentsRecursive = async (folderId, userId, pool) => {
    const contents = {
        files: [],
        folders: []
    };

    // 获取当前文件夹信息
    const [currentFolder] = await pool.query(
        'SELECT * FROM folders WHERE id = ? AND user_id = ?',
        [folderId, userId]
    );

    if (currentFolder.length === 0) {
        return contents;
    }

    // 获取当前文件夹中的文件
    const [files] = await pool.query(
        'SELECT * FROM files WHERE folder_id = ? AND user_id = ?',
        [folderId, userId]
    );
    contents.files.push(...files);

    // 获取子文件夹
    const [subFolders] = await pool.query(
        'SELECT * FROM folders WHERE parent_id = ? AND user_id = ?',
        [folderId, userId]
    );

    // 递归获取每个子文件夹的内容
    for (const folder of subFolders) {
        contents.folders.push(folder);
        const subContents = await getFolderContentsRecursive(folder.id, userId, pool);
        contents.files.push(...subContents.files);
        contents.folders.push(...subContents.folders);
    }

    return contents;
};

const folderController = {
    // 创建文件夹
    createFolder: async (req, res) => {
        try {
            const { folderName, parentId, userId } = req.body;
            console.log(folderName, parentId, userId);
            // 添加数据验证
            if (!folderName || !folderName.trim()) {
                return res.status(400).json({ 
                    error: '文件夹名称不能为空',
                    details: 'Folder name is required'
                });
            }

            if (!userId) {
                return res.status(400).json({ 
                    error: '用户ID不能为空',
                    details: 'User ID is required'
                });
            }

            // 检查同一父文件夹下是否存在同名文件夹
            const [existing] = await pool.query(
                'SELECT id FROM folders WHERE folder_name = ? AND parent_id = ? AND user_id = ?',
                [folderName.trim(), parentId || null, userId]
            );

            if (existing.length > 0) {
                return res.status(400).json({ 
                    error: '该文件夹已存在',
                    details: 'Folder already exists'
                });
            }

            // 创建文件夹
            const [result] = await pool.query(
                'INSERT INTO folders (folder_name, parent_id, user_id) VALUES (?, ?, ?)',
                [folderName.trim(), parentId || null, userId]
            );

            res.json({
                success: true,
                folderId: result.insertId,
                folderName: folderName.trim(),
                parentId: parentId || null,
                userId: userId,
                message: '文件夹创建成功'
            });
        } catch (error) {
            console.error('创建文件夹错误:', error);
            res.status(500).json({ 
                error: '创建文件夹失败', 
                details: error.message 
            });
        }
    },
    // 获取用户的所有根文件夹
    getRootFolders: async (req, res) => {
        try {
            const { userId } = req.params;

            // 验证用户是否存在
            const [users] = await pool.query(
                'SELECT id FROM users WHERE id = ?',
                [userId]
            );

            if (users.length === 0) {
                return res.status(404).json({ 
                    error: '用户不存在',
                    details: 'User not found'
                });
            }

            // 获取根文件夹（parent_id 为 null 的文件夹）
            const [folders] = await pool.query(
                `SELECT 
                    id,
                    folder_name,
                    created_at,
                    (SELECT COUNT(*) FROM folders f2 WHERE f2.parent_id = folders.id) as subfolder_count,
                    (SELECT COUNT(*) FROM files WHERE folder_id = folders.id) as file_count
                FROM folders 
                WHERE user_id = ? AND parent_id IS NULL
                ORDER BY folder_name ASC`,
                [userId]
            );

            res.json({
                success: true,
                folders: folders.map(folder => ({
                    ...folder,
                    subfolder_count: Number(folder.subfolder_count),
                    file_count: Number(folder.file_count)
                }))
            });
        } catch (error) {
            console.error('获取根文件夹错误:', error);
            res.status(500).json({ 
                error: '获取根文件夹失败', 
                details: error.message 
            });
        }
    },
    // 获取文件夹内容
    // 获取文件夹内容
    getFolderContents: async (req, res) => {
        try {
            const { folderId, userId } = req.params;  // 从路由参数获取 userId
    
            console.log('请求参数:', {
                folderId,
                userId,
                type: typeof userId
            });
    
            // 确保 userId 是数字
            const userIdNum = parseInt(userId);
            
            if (isNaN(userIdNum)) {
                return res.status(400).json({ 
                    error: '无效的用户ID',
                    details: 'Invalid user ID format'
                });
            }
    
            // 验证用户是否存在
            const [users] = await pool.query(
                'SELECT id FROM users WHERE id = ?',
                [userIdNum]
            );
    
            console.log('查询到的用户:', users);
    
            if (users.length === 0) {
                return res.status(404).json({ 
                    error: '用户不存在',
                    details: `User with ID ${userIdNum} not found`
                });
            }
    
            // 获取子文件夹
            const [folders] = await pool.query(
                `SELECT 
                    id,
                    folder_name,
                    created_at,
                    (SELECT COUNT(*) FROM folders f2 WHERE f2.parent_id = folders.id) as subfolder_count,
                    (SELECT COUNT(*) FROM files WHERE folder_id = folders.id) as file_count
                FROM folders 
                WHERE parent_id ${folderId === 'root' ? 'IS NULL' : '= ?'} 
                AND user_id = ?
                ORDER BY folder_name ASC`,
                folderId === 'root' ? [userIdNum] : [folderId, userIdNum]
            );
    
            // 获取文件
            const [files] = await pool.query(
                `SELECT 
                    id,
                    filename,
                    file_path,
                    file_size,
                    file_type,
                    upload_time
                FROM files 
                WHERE folder_id ${folderId === 'root' ? 'IS NULL' : '= ?'} 
                AND user_id = ?
                ORDER BY filename ASC`,
                folderId === 'root' ? [userIdNum] : [folderId, userIdNum]
            );
    
            res.json({
                success: true,
                folders: folders.map(folder => ({
                    ...folder,
                    subfolder_count: Number(folder.subfolder_count),
                    file_count: Number(folder.file_count)
                })),
                files
            });
        } catch (error) {
            console.error('获取文件夹内容错误:', error);
            res.status(500).json({ 
                error: '获取文件夹内容失败', 
                details: error.message 
            });
        }
    },

    // 重命名文件夹
    renameFolder: async (req, res) => {
        try {
            const { folderId } = req.params;
            const { newName, userId } = req.body;

            // 检查权限
            const [folder] = await pool.query(
                'SELECT * FROM folders WHERE id = ? AND user_id = ?',
                [folderId, userId]
            );

            if (folder.length === 0) {
                return res.status(403).json({ error: '没有权限修改此文件夹' });
            }

            await pool.query(
                'UPDATE folders SET folder_name = ? WHERE id = ?',
                [newName, folderId]
            );

            res.json({
                success: true,
                message: '文件夹重命名成功'
            });
        } catch (error) {
            res.status(500).json({ error: '重命名文件夹失败', details: error.message });
        }
    },

    // 删除文件夹
    deleteFolder: async (req, res) => {
        try {
            const { folderId } = req.params;
            const { userId } = req.body;

            // 检查权限
            const [folder] = await pool.query(
                'SELECT * FROM folders WHERE id = ? AND user_id = ?',
                [folderId, userId]
            );

            if (folder.length === 0) {
                return res.status(403).json({ error: '没有权限删除此文件夹' });
            }

            // 由于设置了级联删除，直接删除文件夹即可
            await pool.query('DELETE FROM folders WHERE id = ?', [folderId]);

            res.json({
                success: true,
                message: '文件夹删除成功'
            });
        } catch (error) {
            res.status(500).json({ error: '删除文件夹失败', details: error.message });
        }
    },

    // 移动文件夹
    moveFolder: async (req, res) => {
        try {
            const { folderId } = req.params;
            const { newParentId, userId } = req.body;

            // 检查权限
            const [folder] = await pool.query(
                'SELECT * FROM folders WHERE id = ? AND user_id = ?',
                [folderId, userId]
            );

            if (folder.length === 0) {
                return res.status(403).json({ error: '没有权限移动此文件夹' });
            }

            // 检查目标文件夹是否存在
            if (newParentId) {
                const [targetFolder] = await pool.query(
                    'SELECT * FROM folders WHERE id = ? AND user_id = ?',
                    [newParentId, userId]
                );

                if (targetFolder.length === 0) {
                    return res.status(400).json({ error: '目标文件夹不存在' });
                }
            }

            await pool.query(
                'UPDATE folders SET parent_id = ? WHERE id = ?',
                [newParentId || null, folderId]
            );

            res.json({
                success: true,
                message: '文件夹移动成功'
            });
        } catch (error) {
            res.status(500).json({ error: '移动文件夹失败', details: error.message });
        }
    },

    // 下载文件夹
    downloadFolder : async (req, res) => {
        try {
            const { folderId, userId } = req.params;

            console.log('请求参数:', {
                folderId,
                userId,
                params: req.params
            });

            // 验证用户权限
            const [folder] = await pool.query(
                'SELECT * FROM folders WHERE id = ? AND user_id = ?',
                [folderId, userId]
            );
            
            if (folder.length === 0) {
                return res.status(404).json({
                    error: '文件夹不存在或无权访问',
                    details: 'Folder not found or access denied'
                });
            }

            const folderInfo = folder[0];

            // 创建 ZIP 文件
            const archive = archiver('zip', {
                zlib: { level: 9 } // 最大压缩级别
            });

            // 对文件名进行编码
            const safeFileName = encodeURIComponent(folderInfo.folder_name)
                .replace(/['()]/g, escape) // 处理特殊字符
                .replace(/\*/g, '%2A');

            // 设置响应头
            res.setHeader('Content-Type', 'application/zip');
            res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${safeFileName}.zip`);

            // 将压缩流导向响应
            archive.pipe(res);

            // 获取文件夹所有内容
            const contents = await getFolderContentsRecursive(folderId, userId, pool);

            // 创建基础文件夹路径映射
            const folderPaths = new Map();
            folderPaths.set(parseInt(folderId), '');

            // 建立文件夹层级结构
            for (const folder of contents.folders) {
                const parentPath = folderPaths.get(folder.parent_id) || '';
                const currentPath = path.join(parentPath, folder.folder_name);
                folderPaths.set(folder.id, currentPath);
                
                // 创建空文件夹
                archive.append(null, { name: currentPath + '/' });
            }

            // 添加文件到压缩包
            for (const file of contents.files) {
                const folderPath = folderPaths.get(file.folder_id) || '';
                const filePath = path.join(folderPath, file.filename);

                if (fs.existsSync(file.file_path)) {
                    archive.file(file.file_path, { name: filePath });
                } else {
                    console.warn(`文件不存在: ${file.file_path}`);
                }
            }

            // 完成压缩
            await archive.finalize();

        } catch (error) {
            console.error('下载文件夹错误:', error);
            res.status(500).json({
                error: '下载文件夹失败',
                details: error.message
            });
        }
    },

    // 上传文件夹
    uploadFolder: async (req, res) => {
        try {
            if (!req.files || req.files.length === 0) {
                return res.status(400).json({ error: '没有文件被上传' });
            }

            const { userId, parentFolderId } = req.body;
            const uploadedFiles = [];
            const createdFolders = new Map(); // 用于存储已创建的文件夹 {路径: folder_id}

            // 开始事务
            const connection = await pool.getConnection();
            await connection.beginTransaction();

            try {
                // 处理每个文件
                for (const file of req.files) {
                    // 解码文件名和相对路径
                    const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
                    const relativePath = Buffer.from(file.fieldname, 'latin1').toString('utf8');

                    // 分割路径获取文件夹结构
                    const pathParts = relativePath.split('/');
                    pathParts.pop(); // 移除文件名

                    // 确保父文件夹存在
                    let currentFolderId = parentFolderId || null;
                    let currentPath = '';

                    // 创建必要的文件夹结构
                    for (const folderName of pathParts) {
                        if (!folderName) continue;

                        currentPath = currentPath ? `${currentPath}/${folderName}` : folderName;

                        if (createdFolders.has(currentPath)) {
                            currentFolderId = createdFolders.get(currentPath);
                            continue;
                        }

                        // 检查文件夹是否已存在
                        const [existingFolder] = await connection.query(
                            'SELECT id FROM folders WHERE folder_name = ? AND parent_id = ? AND user_id = ?',
                            [folderName, currentFolderId, userId]
                        );

                        if (existingFolder.length > 0) {
                            currentFolderId = existingFolder[0].id;
                            createdFolders.set(currentPath, currentFolderId);
                            continue;
                        }

                        // 创建新文件夹
                        const [result] = await connection.query(
                            'INSERT INTO folders (folder_name, parent_id, user_id) VALUES (?, ?, ?)',
                            [folderName, currentFolderId, userId]
                        );

                        currentFolderId = result.insertId;
                        createdFolders.set(currentPath, currentFolderId);
                    }

                    // 保存文件信息
                    const fileInfo = {
                        filename: originalName,
                        file_path: file.path,
                        file_size: file.size,
                        file_type: file.mimetype.split('/')[0],
                        user_id: userId,
                        folder_id: currentFolderId
                    };

                    // 插入文件记录
                    const [fileResult] = await connection.query(
                        'INSERT INTO files (filename, file_path, file_size, file_type, user_id, folder_id) VALUES (?, ?, ?, ?, ?, ?)',
                        [fileInfo.filename, fileInfo.file_path, fileInfo.file_size, fileInfo.file_type, fileInfo.user_id, fileInfo.folder_id]
                    );

                    uploadedFiles.push({
                        fileId: fileResult.insertId,
                        ...fileInfo
                    });
                }

                await connection.commit();

                res.json({
                    success: true,
                    message: '文件夹上传成功',
                    files: uploadedFiles,
                    folders: Array.from(createdFolders.entries()).map(([path, id]) => ({
                        path,
                        id
                    }))
                });

            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }

        } catch (error) {
            console.error('文件夹上传错误:', error);
            res.status(500).json({ 
                error: '文件夹上传失败', 
                details: error.message 
            });
        }
    },
};

module.exports = folderController;